import json
from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from .models import Student

class IndexView(View):
    def get(self, request):
        return render(request, 'index.html')
    
class StudentsView(View):
    def get(self,request):
        students = []
        for s in Student.objects.all():
            a_student = {
                'id': s.id,
                'name': s.name,
                'gender': s.gender,
                'age': s.age,
                'id_card': s.id_card,
                'phone': s.phone,
                'address': s.address
            }
            students.append(a_student)
        return JsonResponse(students, safe=False)

    def post(self,request):
        s = json.loads(request.body.decode('utf-8'))
        a = {
            'id': int(s['id']),
            'name': s['name'],
            'gender': s['gender'],
            'age': s['age'],
            'id_card': s['id_card'],
            'phone': s['phone'],
            'address': s['address']
        }
        a_student = Student(**a)
        a_student.save()

        return JsonResponse(a, safe=False)

# class StudentView(View):
#     def get(self, request):
#         students = []
#         for s in Student.objects.all():
#             a_student = {
#                 'id': int(s['id']),
#                 'name': s['name'],
#                 'gender': s['gender'],
#                 'age': s['age'],
#                 'id_card': s['id_card'],
#                 'phone': s['phone'],
#                 'address': s['address']
#             }
#             students.append(a_student)
#         return JsonResponse(json.dumps(students), safe=False)

